package com.example.servlet.jiao_test;

import com.example.dao.UsernameDao;
import com.example.dao.UsernameImpl;
import com.example.entity.UserName;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "login", value = "/login")
public class LoginServlet extends HttpServlet {

    public void init() {
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        String scode = (String) session.getAttribute("scode");
        if (scode != null && scode.equals(code)) {
            UsernameDao user = new UsernameImpl();
            UserName users = user.getUsername(username, password);
            if (users != null) {
                request.setAttribute("msg", users.getUsername());
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } else {
                request.setAttribute("mage", "密码输入错误,请重新输入");
                request.getRequestDispatcher("page/login.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("mage", "验证码输入错误,请重新输入");
            request.getRequestDispatcher("page/login.jsp").forward(request, response);
        }
    }


    public void destroy() {
    }
}